package com.jackrain.nea.fc.cp.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.common.PostHandleEvent;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.cp.api.ViewChrorgSaveCmd;
import com.jackrain.nea.fc.cp.mapper.ViewChrorgMapper;
import com.jackrain.nea.fc.utils.ObjectToUtil;
import com.jackrain.nea.fc.utils.UserInformation;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.RuntimeCompute;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;

/**
 * 组织信息-服务开发
 *
 * @author xuxinshuai
 * @create 2017/12/14
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "cp")
public class ViewChrorgSaveCmdImpl extends CommandAdapter implements ViewChrorgSaveCmd {

    @Autowired
    PostHandleEvent postHandleEvent;
    @Override
    public ValueHolder execute(HashMap map) throws NDSException {
        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.DisableCircularReferenceDetect), Feature.OrderedField);
        log.info("ViewChrorgSaveCmdImpl--param-->{}",param);

        if (null == param || param.size() == 0 || param.getJSONArray("data").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }
//        log.debug("-----------传入数据组织-----------");
        ViewChrorgMapper viewChrorgMapper = ApplicationContextHandle.getBean(ViewChrorgMapper.class);
        JSONArray paramArray = param.getJSONArray("data");

        RuntimeCompute runtimeCompute = ApplicationContextHandle.getBean("runtimeCompute");
        runtimeCompute.startRuntime();
        User user = Tools.getUser(UserInformation.USER_NAME);
        JSONArray errArray = new JSONArray();
        //处理pk_fatherorg为空的数据
        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject paramObj = paramArray.getJSONObject(i);
            String orgupid = paramObj.getString("CP_C_ORGUP_ID");
            if (ObjectToUtil.isNullOREmpty(orgupid)) {

                JSONObject errObj = saveOrgDetail(paramObj, viewChrorgMapper, "INOUT", user);

                if (errObj != null && errObj.size() > 0) {
                    errArray.add(errObj);
                }
            }
        }
        //处理pk_fatherorg不为空的数据
        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject paramObj = paramArray.getJSONObject(i);
            String orgupid = paramObj.getString("CP_C_ORGUP_ID");
            if (!ObjectToUtil.isNullOREmpty(orgupid)) {

                JSONObject errObj = new JSONObject();
                //则判断FC组织表中，是否存在HR001_ID=【pk_fatherorg】的数据
                Integer hrCount = viewChrorgMapper.selectorgcount(orgupid);
                if (hrCount > 0) {
                    //查询到符合条件的组织ID，设为CP_C_ORGUP_ID
                    Long hrid = viewChrorgMapper.selectorgId(orgupid);
                    paramObj.put("CP_C_ORGUP_ID", hrid);
                    errObj = saveOrgDetail(paramObj, viewChrorgMapper, "IN", user);
                    if (errObj != null && errObj.size() > 0) {
                        errArray.add(errObj);
                    }

                } else {

                    errObj.put("ErrorMessage", paramObj.getString("ECODE") + "组织的上级组织不存在，数据传输失败！");
                    errArray.add(errObj);
                }
            }
        }
        if (errArray.size() > 0) {
            vh.put("code", -1);
            vh.put("error", errArray);

        } else {
            vh.put("code", 0);
        }
        Double spendTime = runtimeCompute.endRuntime();
        vh.put("spendtime", spendTime);
        log.debug("---------组织执行时间--------->>" + spendTime);
        return vh;

    }

    public JSONObject saveOrgDetail(JSONObject paramObj, ViewChrorgMapper viewChrorgMapper, String orgtype, User user) {

        JSONObject errObj = new JSONObject();

        try {
            // 判断FC中组织表中的数据是否存在HR001_ID=PK_org的数据
            String hr001id = paramObj.getString("HR001_ID");
            Integer orgCount = viewChrorgMapper.selectorgcount(hr001id);
            if (orgCount > 0) {
                //更新数据(统一用ID)
                Long hrorgid = viewChrorgMapper.selectorgId(hr001id);
                JSONObject updateObj = new JSONObject();
                updateObj.put("ECODE", paramObj.getString("ECODE"));
                updateObj.put("ENAME", paramObj.getString("ENAME"));
                updateObj.put("CP_C_ORGUP_ID", paramObj.getString("CP_C_ORGUP_ID"));
                updateObj.put("ISACTIVE", paramObj.getString("ISACTIVE"));
                updateObj.put("ORGTYPE", orgtype);
                if ("INOUT".equals(orgtype)) {
                    updateObj.put("issystem", "Y");
                }
                updateObj.put("MODIFIEDDATE", paramObj.getString("MODIFIEDDATE"));

                JSONObject jo = new JSONObject();
                jo.put("objid", hrorgid);
                jo.put("table", "CP_C_INORG");
                JSONObject fixJo = new JSONObject();
                fixJo.put("CP_C_INORG", updateObj);
                jo.put("fixcolumn", fixJo);
                QuerySessionImpl userquerySession = new QuerySessionImpl(user);
                DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
                event.put("param", jo);
                userquerySession.setEvent(event);
                log.debug("组织更新数据" + jo);
                JSONObject retJo = postHandleEvent.executePostHandle(jo, userquerySession, event, "save");
                if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                    throw new NDSException("" + retJo.get("message") + retJo.get("error"));
                }//                chrorgSaveCmd.execute(userquerySession);

            } else {
                //若不存在则判断FC组织表中是否存在ECODE=CODE的数据
                Integer countcode = viewChrorgMapper.selectcountcode(paramObj.getString("ECODE"));
                if (countcode > 0) {
                    throw new NDSException(paramObj.getString("ECODE") + "组织存在相同编码的数据，新增失败！");
                }
                paramObj.put("ORGTYPE", orgtype);
                if ("INOUT".equals(orgtype)) {
                    paramObj.put("issystem", "Y");
                }
                paramObj.put("CREATIONDATE", paramObj.getString("MODIFIEDDATE"));
                //新增一条数据
                JSONObject jo = new JSONObject();
                jo.put("objid", -1);
                jo.put("table", "CP_C_INORG");

                JSONObject fixJo = new JSONObject();
                fixJo.put("CP_C_INORG", paramObj);
                jo.put("fixcolumn", fixJo);

                log.debug("组织新增数据" + jo);
                QuerySessionImpl userquerySession = new QuerySessionImpl(user);
                DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
                event.put("param", jo);
                userquerySession.setEvent(event);
                JSONObject retJo = postHandleEvent.executePostHandle(jo, userquerySession, event, "save");
                if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                    throw new NDSException("" + retJo.get("message") + retJo.get("error"));
                }//                chrorgSaveCmd.execute(userquerySession);
            }

        } catch (Exception e) {

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            if (e instanceof NDSException) {
                errObj.put("ErrorMessage", e.getMessage());
            } else {
                errObj.put("ErrorMessage", sw.toString());
            }
        }
        return errObj;
    }
}
